package com.example.smallmall.common.api;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 开发公司：SOJSON在线工具 <p>
 * 版权所有：© www.sojson.com
 * 博客地址：http://www.sojson.com/blog/  <p>
 * <p>
 * ---
 * <p>
 * 区分　责任人　日期　　　　说明<br/>
 * 创建　周柏成　2017年11月19日 01:46 　<br/>
 *
 * @author zhou-baicheng
 * @version 1.0<br />
 * @email so@sojson.com
 */
@ControllerAdvice
public class SOJSONExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        //set status code
        httpServletResponse.setStatus(HttpStatus.BAD_REQUEST.value());
        // set content type
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // set character encoding
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
        String message = e.getMessage();
        String returnMessage = "接口请求异常！";
        int status = 400;
        if ("no_city_id".equalsIgnoreCase(message)) {
            returnMessage = "CityId不在返回之内!";
            status = 403;
        }
        if (null != message) {
            returnMessage = message;
        }
        try {
            httpServletResponse.getOutputStream().print(String.format("{\"status\":%s,\"message\":\"%s\"}", status, returnMessage));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return modelAndView;
    }
}
